package donot_to_bonc

import (
	"encoding/json"
	"errors"
	"fmt"
	"lifi"
	"lifi/internal"
	"lifi/plugins/transfers"
	"log"
	"strings"
	"time"
)

const (
	layout       = "2006-01-02 15:04:05"
	goldenLayout = "2006/1/2 15:04:05.000"
)

var mapping map[int]string = make(map[int]string)

type EnvironmentData struct {
	Temperature  string `json:"temperature"`
	LowAccTotal  string `json:"lowAccTotal"`
	HighAccTotal string `json:"highAccTotal"`
}

/*
{"alarm_level":0,"alarm_noti_time":"0001-01-01 00:00:00","code":112,"node_code":"999001001_7","node_id":"076db662-c11e-4d7e-8593-c11dfbffd3db","sampletime":"2023-09-05 08:36:10","value":0.058425084},
*/
type DotonMetrics struct {
	Sampletime    string  `json:"sampletime" yaml:"sampletime"`
	Code          int     `json:"code" yaml:"code"`
	NodeCode      string  `json:"node_code" yaml:"node_code"`
	AlarmNotiTime string  `json:"alarm_noti_time" yaml:"alarm_noti_time"`
	AlarmLevel    int     `json:"alarm_level" yaml:"alarm_level"`
	Value         float64 `json:"value" yaml:"value"`
	NodeID        string  `json:"node_id" yaml:"node_id"`
}

type Donet2BoncTransfer struct {
}

func (d *Donet2BoncTransfer) Init() error {
	mapping[100] = "temperature"
	mapping[101] = "low_acc_total"
	mapping[107] = "vel_total"
	mapping[112] = "high_acc_total"
	mapping[126] = "rotate_speed"
	mapping[129] = "pressure"
	mapping[127] = "displacement"
	return nil
}

func (d *Donet2BoncTransfer) Start(_ lifi.Collector) error {
	return nil
}

func (d *Donet2BoncTransfer) Stop() {
}

func (d *Donet2BoncTransfer) Process(data lifi.Data, acc lifi.Collector) error {
	var dotonMetrics []DotonMetrics
	if bd, ok := data.(lifi.ByteData); ok {
		err := json.Unmarshal(bd.Data, &dotonMetrics)
		if err != nil {
			log.Printf("解析JSON时发生错误:%v,数据：%\n", err, string(bd.Data))
			return err
		}
		grouped := make(map[string][]DotonMetrics)

		for _, item := range dotonMetrics {
			grouped[item.NodeCode] = append(grouped[item.NodeCode], item)
		}
		for nodeCode, m := range grouped {
			tname := fmt.Sprintf("s%s", nodeCode)

			parts := strings.Split(nodeCode, "_")
			if len(parts) != 2 {
				//log.Printf("解析节点编码时发生错误:%v", m)
				return err
			}
			bmpNumber := parts[0]
			chno, _ := internal.ToInt64(strings.Split(nodeCode, "_")[1])
			tags := map[string]string{
				"bmp_number": bmpNumber,
				"chno":       fmt.Sprintf("%d", chno),
			}

			tm, err := internal.ParseTimestamp(time.DateTime, m[0].Sampletime, time.UTC)
			if err != nil {
				tm = time.Now()
			}
			sd := lifi.NewMetricData("sensor_metrics", tname, tags, nil, tm)

			for _, v := range m {
				sd.AddField(mapping[v.Code], v.Value)
			}
			acc.Collect(sd)
		}
		return nil
	}

	return errors.New(string("unknow data:" + data.Group()))
}

var _ lifi.Transfer = &Donet2BoncTransfer{}

func init() {
	transfers.Add("doton_sensor_metrics", func() lifi.Transfer {
		return &Donet2BoncTransfer{}
	})
}
